//
//  CYPubilishQuestionViewController.m
//  cyydt
//
//  Created by chu on 2019/1/21.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYPubilishQuestionViewController.h"
#import "CYXiangShuiTiWenViewController.h"
#import "CYFriendModel.h"
#import "CYCategrayModel.h"
#import "CYSelCategaryView.h"

#define kATFormat  @"@%@ "
#define kATRegular @"@[\\u4e00-\\u9fa5\\w\\-\\_]+ "

@interface CYPubilishQuestionViewController ()<HPGrowingTextViewDelegate, CYXiangShuiTiWenDelegate>
{
    CYCategrayModel *_selBigCateModel;
    CYCategrayModel *_selSmallCateModel;
}
@property (weak, nonatomic) IBOutlet HPGrowingTextView *titleTextView;
@property (weak, nonatomic) IBOutlet HPGrowingTextView *contentTextView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleTextViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentTextViewHeightConstraint;
@property (weak, nonatomic) IBOutlet UIView *imagesView;
@property (weak, nonatomic) IBOutlet UIButton *addHangyeBtn;
@property (weak, nonatomic) IBOutlet UIButton *selDaoShiBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selHangYeHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selDaoShiHeightConstraint;
@property (weak, nonatomic) IBOutlet UIView *selHangYeView;
@property (weak, nonatomic) IBOutlet UIView *selDaoShiView;

@property (nonatomic, strong) NSMutableArray *imagesArr;
@property (nonatomic, strong) NSMutableArray *pathArr;

@property (strong, nonatomic) HXPhotoManager *manager;
@property (nonatomic, strong) NSMutableArray* categaryArr;
@property (nonatomic, strong) CYProjectModel* wentiModel;

@end

@implementation CYPubilishQuestionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"提问";
    [self getAllCategary];
    self.titleTextView.delegate = self;
    self.titleTextView.font = [UIFont systemFontOfSize:15];
    self.titleTextView.minNumberOfLines = 1;
    self.titleTextView.maxNumberOfLines = 10;
    self.titleTextView.placeholder = @"请输入您的标题（5-30字）";
    self.titleTextView.returnKeyType = UIReturnKeySend;
    self.titleTextView.enablesReturnKeyAutomatically = YES;
    
    self.contentTextView.delegate = self;
    self.contentTextView.font = [UIFont systemFontOfSize:15];
    self.contentTextView.placeholder = @"请描述您的问题，如创业资金、地段、行业问题等...";
    self.contentTextView.maxHeight = 10000;
    self.contentTextView.contentInset = UIEdgeInsetsMake(15, 15, 15, 15);
    self.contentTextView.enablesReturnKeyAutomatically = YES;

    self.addHangyeBtn.layer.cornerRadius = self.addHangyeBtn.frame.size.height / 2;
//    self.addHangyeBtn.layer.borderWidth = 1;
//    self.addHangyeBtn.layer.borderColor = RGBOF(0xE3E3E3).CGColor;
    self.addHangyeBtn.layer.masksToBounds = YES;
    
    [self addImage];
    
    [self rightBarItemWithTitle:@"发布"];
    
    if (self.type == TiWenType_XiangTaTiWen) {
        NSInteger index = self.contentTextView.text.length;
        
        UITextView *textView = self.contentTextView.internalTextView;
        
        NSString *insertString = [NSString stringWithFormat:kATFormat,self.nickname];
        NSMutableString *string = [NSMutableString stringWithString:textView.text];
        [string insertString:insertString atIndex:index];
        self.contentTextView.text = string;
        [self.contentTextView becomeFirstResponder];
        textView.selectedRange = NSMakeRange(index + insertString.length, 0);
    }else if (self.type == TiWenType_WoLaiHuiDa){
        self.selHangYeHeightConstraint.constant = 0;
        self.selDaoShiHeightConstraint.constant = 0;
        self.selHangYeView.hidden = YES;
        self.selDaoShiView.hidden = YES;
        self.titleTextView.text = self.biaoti;
        self.titleTextView.userInteractionEnabled = NO;
        self.title = @"回答";
    }else if (self.type == TiWenType_BoHui){
        [self getWentiDetail];
    }

}

- (void)RighttouchEvent {
    [self.view endEditing:YES];
    //上传图片
    if (self.pathArr.count != self.imagesArr.count) {
        return;
    }
    // 验证输入
    // 1、验证内容
    if ([NSString stringIsNull:self.titleTextView.text] || self.titleTextView.text.length < 5) {
        [self.view makeToast:@"标题长度不能小于5个字符" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    // 2、验证title
    if ([NSString stringIsNull:self.contentTextView.text] || self.contentTextView.text.length < 20) {
        [self.view makeToast:@"内容长度不能小于20个字符" duration:1.5 position:CSToastPositionCenter];
        return;
    }

    [EasyShowLodingView showLoding];
    
    NSString *pathStr = [self.pathArr componentsJoinedByString:@","];
    NSArray *matches = [self findAllAt];
    NSMutableArray *atArr = [NSMutableArray arrayWithCapacity:0];
    for (NSTextCheckingResult *match in matches)
    {
        NSString *str = [self.contentTextView.text substringWithRange:match.range];
        [atArr addObject:str];
    }
    
    NSString *allAt = [atArr componentsJoinedByString:@","];
    NSString *url = @"";
    if (self.type == TiWenType_WoLaiHuiDa){
        url = [NSString stringWithFormat:@"%@%@",User_HOST, @"ask/answer"];
    }else{
        url = [NSString stringWithFormat:@"%@%@",User_HOST, @"ask/question"];
    }
    NSDictionary *param = @{};
    if (self.type == TiWenType_WoLaiHuiDa){
        NSMutableArray *pathArr = [NSMutableArray array];
        for (int i = 0; i < self.pathArr.count; i++) {
            NSString *img = self.pathArr[i];
            img = [NSString stringWithFormat:@"<img src=\"%@\">",img];
            [pathArr addObject:img];
        }
        
        NSMutableArray *muarr = [NSMutableArray arrayWithCapacity:0];
        [muarr addObject:self.contentTextView.text];
        [muarr addObjectsFromArray:pathArr];
        param = @{@"title":self.titleTextView.text, @"questionId":self.questionId, @"tempContent":self.contentTextView.text, @"contents":muarr};
    }else{
        NSNumber *category = @2648;
        NSNumber *subCategory = @2651;
        
        if (_selBigCateModel) {
            category = _selBigCateModel.catid;
        }
        if (_selSmallCateModel) {
            subCategory = _selSmallCateModel.catid;
        }
        
        param = @{@"title":self.titleTextView.text, @"tempDescription":self.contentTextView.text, @"images":pathStr, @"category":category, @"subCategory":subCategory, @"source":@6, @"type":self.selDaoShiBtn.selected == YES ? @"1" : @"0", @"at":allAt};
    }
    
    NSLog(@"param --- %@",param);
    [[XBRequest sharedInstance] postDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"发布问题---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                [[UIApplication sharedApplication].keyWindow makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                [[AppDelegate sharedAppDelegate] popViewController];
                
            }else{
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];

}

- (void)updateImageWithData:(NSData *)imageData{
    
    //将图片上传到服务器
    [EasyShowLodingView showLoding];
    NSString *str = @"file";
    NSString *urlString = [User_HOST stringByAppendingString:str];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    if ([YLUserInfo isLogIn]) {
        [manager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"target"] = @1;
    //接收类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    [manager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageDatas = imageData;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageDatas
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"responseObject--- %@",responseObject);
        //上传成功
        if ([responseObject[Response_code] integerValue] == Response_value) {
            if ([responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                NSArray *data = responseObject[@"data"];
                if (data.count > 0) {
                    NSDictionary *dic = [data firstObject];
                    if (self.type == TiWenType_WoLaiHuiDa) {
                        [self.pathArr addObject:dic[@"fullpath"]];
                    }else{
                        [self.pathArr addObject:dic[@"path"]];
                    }
                }
            }
            
        }else if([responseObject[@"returnCode"] integerValue] == 4000){
            
        }else{
            [self.view makeToast:responseObject[@"returnMessage"] duration:1.5 position:CSToastPositionCenter];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error -- %@",error);
        [EasyShowLodingView hidenLoding];
        //上传失败
        [self.view makeToast:@"上传失败" duration:1.5 position:CSToastPositionCenter];
    }];
}

#pragma mark - UITextViewDelegate

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    if (growingTextView == self.contentTextView) {
        self.contentTextViewHeightConstraint.constant = height;
    }else{
       self.titleTextViewHeightConstraint.constant = height;
    }
    
    [self.view layoutIfNeeded];
}

- (BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView
{
    [self.titleTextView resignFirstResponder];
    return YES;
}

- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (growingTextView == self.titleTextView) {
        NSString *comcatstr = [growingTextView.text stringByReplacingCharactersInRange:range withString:text];
        NSInteger caninputlen = 30 - comcatstr.length;
        if (caninputlen >= 0){
            return YES;
        }else{
            
            NSInteger len = text.length + caninputlen;
            //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
            NSRange rg = {0,MAX(len,0)};
            if (rg.length >0){
                
                NSString *s =@"";
                
                //判断是否只普通的字符或asc码(对于中文和表情返回NO)
                
                BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
                
                if (asc) {
                    
                    s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
                    
                }else{
                    
                    __block NSInteger idx =0;
                    
                    __block NSString  *trimString =@"";//截取出的字串
                    
                    //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个
                    
                    [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                     
                                             options:NSStringEnumerationByComposedCharacterSequences
                     
                                          usingBlock: ^(NSString* substring,NSRange substringRange,NSRange enclosingRange,BOOL* stop) {
                                              
                                              if (idx >= rg.length) {
                                                  
                                                  *stop =YES;//取出所需要就break，提高效率
                                                  
                                                  return ;
                                              }
                                              
                                              trimString = [trimString stringByAppendingString:substring];
                                              
                                              idx++;
                                              
                                          }];
                    
                    s = trimString;
                    
                }
                
                //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
                
                [growingTextView setText:[growingTextView.text stringByReplacingCharactersInRange:range withString:s]];
                
                //既然是超出部分截取了，哪一定是最大限制了。
                
                
            }
            return NO;
        }
    }
    if (growingTextView == self.contentTextView) {
        NSString *comcatstr = [growingTextView.text stringByReplacingCharactersInRange:range withString:text];
        NSInteger caninputlen = 500 - comcatstr.length;
        if (caninputlen >= 0){
            return YES;
        }else{
            
            NSInteger len = text.length + caninputlen;
            //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
            NSRange rg = {0,MAX(len,0)};
            if (rg.length >0){
                
                NSString *s =@"";
                
                //判断是否只普通的字符或asc码(对于中文和表情返回NO)
                
                BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
                
                if (asc) {
                    
                    s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
                    
                }else{
                    
                    __block NSInteger idx =0;
                    
                    __block NSString  *trimString =@"";//截取出的字串
                    
                    //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个
                    
                    [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                     
                                             options:NSStringEnumerationByComposedCharacterSequences
                     
                                          usingBlock: ^(NSString* substring,NSRange substringRange,NSRange enclosingRange,BOOL* stop) {
                                              
                                              if (idx >= rg.length) {
                                                  
                                                  *stop =YES;//取出所需要就break，提高效率
                                                  
                                                  return ;
                                              }
                                              
                                              trimString = [trimString stringByAppendingString:substring];
                                              
                                              idx++;
                                              
                                          }];
                    
                    s = trimString;
                    
                }
                
                //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
                
                [growingTextView setText:[growingTextView.text stringByReplacingCharactersInRange:range withString:s]];
                
                //既然是超出部分截取了，哪一定是最大限制了。
                
                
            }
            return NO;
        }
    }

    if ([text isEqualToString:@""])
    {
        NSRange selectRange = growingTextView.selectedRange;
        if (selectRange.length > 0)
        {
            //用户长按选择文本时不处理
            return YES;
        }
        
        // 判断删除的是一个@中间的字符就整体删除
        NSMutableString *string = [NSMutableString stringWithString:growingTextView.text];
        NSArray *matches = [self findAllAt];
        
        BOOL inAt = NO;
        NSInteger index = range.location;
        for (NSTextCheckingResult *match in matches)
        {
            NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
            if (NSLocationInRange(range.location, newRange))
            {
                inAt = YES;
                index = match.range.location;
                [string replaceCharactersInRange:match.range withString:@""];
                break;
            }
        }
        
        if (inAt)
        {
            growingTextView.text = string;
            growingTextView.selectedRange = NSMakeRange(index, 0);
            return NO;
        }
    }
    
    //判断是回车键就发送出去
//    if ([text isEqualToString:@"\n"])
//    {
//        [self.comments addObject:growingTextView.text];
//        self.growingTextView.text = @"";
//        [self.growingTextView resignFirstResponder];
//        [self.tableView reloadData];
//        return NO;
//    }
    
    return YES;
}

- (void)growingTextViewDidChange:(HPGrowingTextView *)growingTextView
{
    UITextRange *selectedRange = growingTextView.internalTextView.markedTextRange;
    NSString *newText = [growingTextView.internalTextView textInRange:selectedRange];
    
    if (newText.length < 1)
    {
        // 高亮输入框中的@
        UITextView *textView = self.contentTextView.internalTextView;
        NSRange range = textView.selectedRange;
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:textView.text];
        [string addAttribute:NSForegroundColorAttributeName value:RGBOF(0x666666) range:NSMakeRange(0, string.string.length)];
        
        NSArray *matches = [self findAllAt];
        
        for (NSTextCheckingResult *match in matches)
        {
            [string addAttribute:NSForegroundColorAttributeName value:RGBOF(0x4173AF) range:NSMakeRange(match.range.location, match.range.length - 1)];
        }
        
        textView.attributedText = string;
        textView.selectedRange = range;
    }
}

- (void)growingTextViewDidChangeSelection:(HPGrowingTextView *)growingTextView
{
    // 光标不能点落在@词中间
    NSRange range = growingTextView.selectedRange;
    if (range.length > 0)
    {
        // 选择文本时可以
        return;
    }
    
    NSArray *matches = [self findAllAt];
    
    for (NSTextCheckingResult *match in matches)
    {
        NSRange newRange = NSMakeRange(match.range.location + 1, match.range.length - 1);
        if (NSLocationInRange(range.location, newRange))
        {
            growingTextView.internalTextView.selectedRange = NSMakeRange(match.range.location + match.range.length, 0);
            break;
        }
    }
}


#pragma mark - Private

- (NSArray<NSTextCheckingResult *> *)findAllAt
{
    // 找到文本中所有的@
    NSString *string = self.contentTextView.text;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:kATRegular options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regex matchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, [string length])];
    return matches;
}

- (void)addImage{
    [self.imagesView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat margin = 5;
    CGFloat width = (kWindowW - 30 - 20) / 5;
    CGFloat height = (kWindowW - 30 - 20) / 5;
    NSMutableArray *muarr = [NSMutableArray arrayWithCapacity:0];
    [muarr addObjectsFromArray:self.imagesArr];
    [muarr addObject:[UIImage imageNamed:@"tiwen_tup"]];
    if (self.type == TiWenType_TiWen) {
        [muarr addObject:[UIImage imageNamed:@"tiwen_huidaren"]];
    }else if (self.type == TiWenType_XiangTaTiWen){
        [muarr addObject:[UIImage imageNamed:@"tiwen_huidaren"]];
    }else if (self.type == TiWenType_WoLaiHuiDa){
        
    }else if (self.type == TiWenType_BoHui){
        [muarr addObject:[UIImage imageNamed:@"tiwen_huidaren"]];
    }

    for (int i = 0; i < muarr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(15 + i * width + i * margin, 0, width, height);
        [btn setImage:muarr[i] forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.imagesView addSubview:btn];
    }
}

- (void)btnAction:(UIButton *)sender{
    if (self.imagesArr.count == 0) {
        if (sender.tag == 0) {
            [self takePhoto];
        }if (sender.tag == 1) {
            [self selFriend];
        }
    }else if (self.imagesArr.count == 1){
        if (sender.tag == 1) {
            [self takePhoto];
        }if (sender.tag == 2) {
            [self selFriend];
        }
    }else if (self.imagesArr.count == 2){
        if (sender.tag == 2) {
            [self takePhoto];
        }if (sender.tag == 3) {
            [self selFriend];
        }
    }else{
        if (sender.tag == 3) {
            [self takePhoto];
        }if (sender.tag == 4) {
            [self selFriend];
        }
    }
}

- (void)takePhoto{
    [self hx_presentSelectPhotoControllerWithManager:self.manager didDone:^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL isOriginal, UIViewController *viewController, HXPhotoManager *manager) {
        [UINavigationBar appearance].translucent = NO;
        [self.imagesArr removeAllObjects];
        [self.pathArr removeAllObjects];
        NSLog(@"block - all - %@",allList);
        NSLog(@"block - photo - %@",photoList);
        NSLog(@"block - video - %@",videoList);
        if (photoList.count > 0) {
            for (int i = 0; i < photoList.count; i++) {
                HXPhotoModel *model = photoList[i];
                [model requestPreviewImageWithSize:PHImageManagerMaximumSize startRequestICloud:^(PHImageRequestID iCloudRequestId, HXPhotoModel *model) {
                    // 如果照片在iCloud上会去下载,此回调代表开始下载iCloud上的照片
                    // 如果照片在本地存在此回调则不会走
                } progressHandler:^(double progress, HXPhotoModel *model) {
                    // iCloud下载进度
                    // 如果为网络图片,则是网络图片的下载进度
                } success:^(UIImage *image, HXPhotoModel *model, NSDictionary *info) {
                    // 获取成功
                    [self.imagesArr addObject:image];
                    [self addImage];
                    [self updateImageWithData:UIImageJPEGRepresentation(image, 0.5)];
                    
                } failed:^(NSDictionary *info, HXPhotoModel *model) {
                    // 获取失败
                }];
            }
        }
    } cancel:^(UIViewController *viewController, HXPhotoManager *manager) {
        NSLog(@"block - 取消了");
        [UINavigationBar appearance].translucent = NO;
    }];
}

- (void)selFriend{
    NSArray *matches = [self findAllAt];
    if (matches.count >= 5) {
        [self.view makeToast:@"@人数不能超过5个" duration:1.5 position:CSToastPositionCenter];
        return;
    }
    CYXiangShuiTiWenViewController *tiwen = [[CYXiangShuiTiWenViewController alloc] init];
    tiwen.delegate = self;
    [[AppDelegate sharedAppDelegate] pushViewController:tiwen];
}

#pragma mark - 选择向谁提问结果
- (void)doneFinishWithArr:(NSArray *)arr{

    NSArray *matches = [self findAllAt];
    NSMutableArray *atArr = [NSMutableArray arrayWithCapacity:0];
    for (NSTextCheckingResult *match in matches)
    {
        NSString *str = [self.contentTextView.text substringWithRange:match.range];
        NSString *value = [str substringWithRange:NSMakeRange(1, str.length - 2)];
        [atArr addObject:value];
    }
    
    if (atArr.count > 0) {
        NSMutableArray *muArr = [NSMutableArray arrayWithArray:arr];
        for (int i = 0; i < arr.count; i++) {
            CYFriendModel *model = arr[i];
            if ([atArr containsObject:model.nickName]) {
                [muArr removeObject:model];
            }
        }
        for (CYFriendModel *model in muArr) {
            NSInteger index = self.contentTextView.text.length;
            
            UITextView *textView = self.contentTextView.internalTextView;
            
            NSString *insertString = [NSString stringWithFormat:kATFormat,model.nickName];
            NSMutableString *string = [NSMutableString stringWithString:textView.text];
            [string insertString:insertString atIndex:index];
            self.contentTextView.text = string;
            
            [self.contentTextView becomeFirstResponder];
            textView.selectedRange = NSMakeRange(index + insertString.length, 0);
        }
    }else{
        for (CYFriendModel *model in arr) {
            NSInteger index = self.contentTextView.text.length;
            
            UITextView *textView = self.contentTextView.internalTextView;
            
            NSString *insertString = [NSString stringWithFormat:kATFormat,model.nickName];
            NSMutableString *string = [NSMutableString stringWithString:textView.text];
            [string insertString:insertString atIndex:index];
            self.contentTextView.text = string;
            
            [self.contentTextView becomeFirstResponder];
            textView.selectedRange = NSMakeRange(index + insertString.length, 0);
        }
    }
    
    
}

#pragma mark - 选择行业
- (IBAction)addHangyeAction:(UIButton *)sender {
    [self.view endEditing:YES];
    NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"CYSelCategaryView" owner:self options:nil];
    CYSelCategaryView *backView = [nibView objectAtIndex:0];
    backView.frame = CGRectMake(0, 0, kWindowW, 410);
    backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    backView.dataSourceArr = self.categaryArr;
    backView.haveSmallCategary = YES;
    __weak typeof(self)weakself = self;
    backView.block = ^(CYCategrayModel * _Nonnull bigCateModel, CYCategrayModel * _Nonnull smallCateModel) {
        self->_selBigCateModel = bigCateModel;
        self->_selSmallCateModel = smallCateModel;
        if (bigCateModel) {
            if (smallCateModel) {
                [self.addHangyeBtn setTitle:[NSString stringWithFormat:@"%@-%@",bigCateModel.catname, smallCateModel.catname] forState:UIControlStateNormal];
            }else{
                [self.addHangyeBtn setTitle:[NSString stringWithFormat:@"%@",bigCateModel.catname] forState:UIControlStateNormal];
            }
            [weakself.view layoutIfNeeded];
            [weakself addDelBtn];
        }else{
            [self.addHangyeBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
        }
    };
    [GKCover translucentCoverFrom:[UIApplication sharedApplication].keyWindow content:backView animated:YES showBlock:^{
        // 显示出来时的block
        NSLog(@"弹窗显示了，6不6");
    } hideBlock:^{
        // 移除后的block
        NSLog(@"弹窗消失了，555");
    }];
}

- (void)addDelBtn{
    for (UIView *view in self.selHangYeView.subviews) {
        if (view.tag == 10033) {
            [view removeFromSuperview];
        }
    }
    UIButton *btn = [[UIButton alloc] init];
    btn.tag = 10033;
    [btn setImage:[UIImage imageNamed:@"ss_gb"] forState:UIControlStateNormal];
    [self.selHangYeView addSubview:btn];
    [btn addTarget:self action:@selector(delCate:) forControlEvents:UIControlEventTouchUpInside];
    CGFloat marginLeft = self.addHangyeBtn.frame.size.width + 7;
    __weak typeof(self)weakself = self;
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(14);
        make.height.mas_equalTo(14);
        make.left.equalTo(weakself.selHangYeView).with.mas_equalTo(marginLeft);
        make.top.equalTo(weakself.selHangYeView).with.mas_equalTo(45);
    }];
}

- (void)delCate:(UIButton *)sender{
    [self.addHangyeBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
    _selBigCateModel = nil;
    _selSmallCateModel = nil;
    [sender removeFromSuperview];
}

#pragma mark - 获取所有分类
- (void)getAllCategary{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"categories"];
    NSDictionary *param = @{@"type":@4};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取所有分类 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSArray class]]) {
                    NSArray *data = responseResult[@"data"];
                    [self.categaryArr removeAllObjects];
                    for (NSDictionary *dic in data) {
                        NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                        [muDic setObject:dic[@"name"] forKey:@"catname"];
                        [muDic setObject:dic[@"id"] forKey:@"catid"];
                        [muDic setObject:dic[@"childCates"] forKey:@"child"];
                        [muDic removeObjectForKey:@"id"];
                        [muDic removeObjectForKey:@"name"];
                        [muDic removeObjectForKey:@"childCates"];
                        CYCategrayModel *model = [CYCategrayModel modelWithDictionary:muDic];
                        [self.categaryArr addObject:model];
                    }
                    if (self.wentiModel) {
                        [self initCate];
                    }
                }
            }else{
                
            }
        }
    }];
}

- (IBAction)selDaoShiAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}

#pragma mark - 获取问题详情
- (void)getWentiDetail{
    NSString *url = [NSString stringWithFormat:@"%@%@",HOST, @"index/view"];
    NSDictionary *param = @{@"id":self.wentiId, @"type":@"4"};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"获取问题详情 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage];
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                if ([responseResult[@"data"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *data = responseResult[@"data"];
                    self.wentiModel = [CYProjectModel mj_objectWithKeyValues:data];
                    [self initData];
                }
            }else{
                [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

- (void)initData{
    self.titleTextView.text = self.wentiModel.title;
    self.contentTextView.text = self.wentiModel.content;
    [self.imagesArr removeAllObjects];
    [self.pathArr removeAllObjects];

    NSArray *images = self.wentiModel.img_url;
    for (int i = 0; i < images.count; i++) {
        NSString *imageUrl = images[i];
        NSArray *urls = [imageUrl componentsSeparatedByString:@"/"];
        NSArray *values = [urls subarrayWithRange:NSMakeRange(3, urls.count - 3)];
        NSString *value = [values componentsJoinedByString:@"/"];
        NSLog(@"value -- %@",value);
        [self.pathArr addObject:value];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:images[i]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            [self.imagesArr addObject:image];
            [self addImage];
        }];
    }
    if (self.categaryArr.count > 0) {
        [self initCate];
    }
}

- (void)initCate{
    for (CYCategrayModel *bigCate in self.categaryArr) {
        if ([bigCate.catid integerValue] == [self.wentiModel.big_catid integerValue]) {
            _selBigCateModel = bigCate;
            for (CYCategrayModel *smallCate in bigCate.child) {
                if ([smallCate.catid integerValue] == [self.wentiModel.catid integerValue]){
                    _selSmallCateModel = smallCate;
                }
            }
        }
    }
    if (_selBigCateModel) {
        if (_selSmallCateModel) {
            [self.addHangyeBtn setTitle:[NSString stringWithFormat:@"%@-%@",_selBigCateModel.catname, _selSmallCateModel.catname] forState:UIControlStateNormal];
        }else{
            [self.addHangyeBtn setTitle:[NSString stringWithFormat:@"%@",_selBigCateModel.catname] forState:UIControlStateNormal];
        }
        [self.view layoutIfNeeded];
        [self addDelBtn];
    }else{
        [self.addHangyeBtn setTitle:@"+ 添加" forState:UIControlStateNormal];
    }
}

- (NSMutableArray *)imagesArr{
    if (!_imagesArr) {
        _imagesArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _imagesArr;
}

- (NSMutableArray *)pathArr{
    if (!_pathArr) {
        _pathArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _pathArr;
}

- (NSMutableArray *)categaryArr{
    if (!_categaryArr) {
        _categaryArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _categaryArr;
}

- (HXPhotoManager *)manager
{
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.photoMaxNum = 3;
        _manager.configuration.deleteTemporaryPhoto = NO;
        _manager.configuration.saveSystemAblum = YES;
        _manager.configuration.creationDateSort = YES;
        _manager.configuration.supportRotation = NO;
        _manager.configuration.cameraCellShowPreview = NO;
        _manager.configuration.navBarBackgroudColor = [UIColor whiteColor];
        _manager.configuration.navigationTitleColor = [UIColor blackColor];
        
        _manager.configuration.originalNormalImageName = @"zpgl_fb_wxz";
        _manager.configuration.originalSelectedImageName = @"zpgl_fb_xz";
        _manager.configuration.restoreNavigationBar = YES;
        _manager.configuration.navigationBar = ^(UINavigationBar *navigationBar, UIViewController *viewController) {
            [navigationBar setBackgroundImage:[UIImage imageNamed:@"APPCityPlayer_bannerGame"] forBarMetrics:UIBarMetricsDefault];
            navigationBar.barTintColor = [UIColor whiteColor];
            navigationBar.tintColor = [UIColor blackColor];
        };
        //        _manager.configuration.sectionHeaderTranslucent = NO;
        //                _manager.configuration.navBarBackgroudColor = [UIColor redColor];
        //        _manager.configuration.sectionHeaderSuspensionBgColor = [UIColor redColor];
        //        _manager.configuration.sectionHeaderSuspensionTitleColor = [UIColor whiteColor];
        //        _manager.configuration.statusBarStyle = UIStatusBarStyleLightContent;
        //        _manager.configuration.selectedTitleColor = [UIColor redColor];
        
        //        _manager.configuration.requestImageAfterFinishingSelection = YES;
        
        __weak typeof(self) weakSelf = self;
        _manager.configuration.photoListBottomView = ^(HXDatePhotoBottomView *bottomView) {
        };
        _manager.configuration.previewBottomView = ^(HXDatePhotoPreviewBottomView *bottomView) {
        };
        _manager.configuration.albumListCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"albumList:%@",collectionView);
        };
        _manager.configuration.photoListCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"photoList:%@",collectionView);
        };
        _manager.configuration.previewCollectionView = ^(UICollectionView *collectionView) {
            //            NSSLog(@"preview:%@",collectionView);
        };
        //        _manager.configuration.movableCropBox = YES;
        //        _manager.configuration.movableCropBoxEditSize = YES;
        //        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        
        // 使用自动的相机  这里拿系统相机做示例
        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, HXPhotoConfigurationCameraType cameraType, HXPhotoManager *manager) {
            
            // 这里拿使用系统相机做例子
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = (id)weakSelf;
            imagePickerController.allowsEditing = NO;
            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
            NSArray *arrMediaTypes;
            if (cameraType == HXPhotoConfigurationCameraTypePhoto) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
            }else if (cameraType == HXPhotoConfigurationCameraTypeVideo) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
            }else {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
            }
            [imagePickerController setMediaTypes:arrMediaTypes];
            // 设置录制视频的质量
            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
            //设置最长摄像时间
            [imagePickerController setVideoMaximumDuration:60.f];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            [viewController presentViewController:imagePickerController animated:YES completion:nil];
        };
        //        _manager.shouldSelectModel = ^NSString *(HXPhotoModel *model) {
        //            // 如果return nil 则会走默认的判断是否达到最大值
        //            //return nil;
        //            return @"Demo1 116 - 120 行注释掉就能选啦~\(≧▽≦)/~";
        //        };
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.photoCanEdit = YES;
    }
    return _manager;
}

@end
